package com.rd.student.ruanjian.class3.gaochenxi.LianXi3.NumberSeven;

public class NumberSeven {
   private int flag = 1;

   private int i = 0;

   private int j = 0;

   //取一个ai[i]中的数组之后,阻塞ai[i],唤醒ac[i];
   //取一个ac[i]中的数组元素之后，阻塞下ac[i],唤醒下ai[i];


   int[] ai = {1, 2, 3, 4, 5, 6, 7};
   String[] ac = {"A", "B", "C", "D", "E", "F", "G"};

   public synchronized void print1() {
      while (flag != 1) {
         try {
            wait();
         } catch (InterruptedException e) {
            throw new RuntimeException(e);
         }
      }
      if (i < ai.length) {
         System.out.print(ai[i]);
         i++;
      } else {
         return;
      }

      flag = 2;
      notifyAll();
   }

   public synchronized void print2() {

      while (flag != 2) {
         try {
            wait();
         } catch (InterruptedException e) {
            throw new RuntimeException(e);
         }
      }
      if (j < ac.length) {
         System.out.print(ac[j]);
         j++;
      } else {
         return;
      }
      flag = 1;
      notifyAll();
   }

   public static void main(String[] args) {
      NumberSeven numberSeven = new NumberSeven();
      for (int i = 0; i < 8; i++) {
         new Thread(new Runnable() {
            @Override
            public void run() {
               numberSeven.print1();
            }
         }).start();

         new Thread(new Runnable() {
            @Override
            public void run() {
               numberSeven.print2();
            }
         }).start();
      }
   }
};


